﻿/**********************************************
* 作    者：YuBing
* 创建日期：2009年02月20日
* 描    述：Castle容器管理
* 修改日期：2009年07月07日
***********************************************/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using System.Web;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;

namespace Meqs.Logic
{
    /// <summary>
    /// ContainerAccessorUtil
    /// Castle容器管理
    /// 
    /// 修改记录:
    ///     2009/04/20: 代码创建
    ///     2009/07/07: 新增对web及类库工程的判断，读取配置文件的IsWeb节点
    /// <author>
    ///     <name>YuBing</name>
    ///     <date>2009/07/07</date>
    /// </author>
    /// </summary>
    public class ContainerAccessorUtil
    {
        private ContainerAccessorUtil()
        {
        }

        /// <summary>
        /// Obtain the Cuyahoga container.
        /// </summary>
        /// <returns></returns>
        public static IWindsorContainer GetContainer()
        {
            string isWeb = ConfigurationManager.AppSettings["IsWeb"];
            return isWeb == "Yes" ? GetHttpContainer() : GetTestContainer();
        }


        #region Web方式

        private static IWindsorContainer GetHttpContainer()
        {
            IContainerAccessor containerAccessor = HttpContext.Current.ApplicationInstance as IContainerAccessor;

            if (containerAccessor == null)
            {
                throw new Exception("You must extend the HttpApplication in your web project " +
                    "and implement the IContainerAccessor to properly expose your container instance");
            }

            IWindsorContainer container = containerAccessor.Container as IWindsorContainer;

            if (container == null)
            {
                throw new Exception("The container seems to be unavailable in " +
                    "your HttpApplication subclass");
            }

            return container;
        }

        #endregion

        #region 类库方式

        private static readonly IWindsorContainer _container = new WindsorContainer(new XmlInterpreter());

        private static IWindsorContainer GetTestContainer()
        {
            return _container;
        }

        #endregion
    } 
}